﻿$(document).ready(function () {
	$(".schedule-dropdown").change(function () {
		var ajax_data = parseInt($(".schedule-dropdown").val());
		if (ajax_data < 1)
			return;

		$.ajax({
			url: "../seats.aspx",
			data: "sched=" + ajax_data,
			type: "get",
			beforeSend: function () {
				showLoading();
			},
			success: function (result) {
				hideLoading();
				$(".seat-wrap").html(result);
			},
			error: function (err1, err2, err3) {
				hideLoading();
				alert(err1 + " || " + err2 + " || " + err3);
			}
		});
	});
});

function SeatClicked(seat) {
	if ($(seat).hasClass("seatReserved")) {
		if (! confirm("The seat is reserved. Unreserve?"))
			return;
		$(seat).removeClass("seatReserved").addClass("seatFree");
		var seatId = $(seat).find("input[type=hidden]").val();
		var schedId = $("#schedule-id").val();
		unreserveSeat(schedId, seatId);
	} else if ($(seat).hasClass("seatIdle")) {
		if (!confirm("The seat is reserved. Unreserve?"))
			return;
		$(seat).removeClass("seatIdle").addClass("seatFree");
		var seatId = $(seat).find("input[type=hidden]").val();
		var schedId = $("#schedule-id").val();
		unreserveSeat(schedId, seatId);
	} else if ($(seat).hasClass("seatFree")) {
		if ($(".name_input").val() != "" && $(".phone_input").val() != "")
			$(seat).removeClass("seatFree").addClass("seatIdle");
		else
			$(seat).removeClass("seatFree").addClass("seatReserved");
		seatId = $(seat).find("input[type=hidden]").val();
		schedId = $("#schedule-id").val();
		reserveSeat(schedId, seatId);
	}
}

function reserveSeat(schedId, seatId) {
	var requestData = "cmd=add&schedid=" + schedId + "&seatid=" + seatId;

	var name = $(".name_input").val();
	var phone = $(".phone_input").val();
	if (name != "" && phone != "")
		requestData += "&name=" + name + "&phone=" + phone;

	$.ajax({
		url: "../ajax/reserve.aspx",
		data: requestData,
		beforeSend: function () {
			showLoading();
		},
		success: function (result) {
			hideLoading();
			if (result != "success")
				alert("Error! Try again later..");
		},
		error: function (err1, err2, err3) {
			hideLoading();
			alert(err1 + " || " + err2 + " || " + err3);
		}
	});
}

function unreserveSeat(schedId, seatId) {
	var requestData = "cmd=remove&schedid=" + schedId + "&seatid=" + seatId;

	$.ajax({
		url: "../ajax/reserve.aspx",
		data: requestData,
		beforeSend: function () {
			showLoading();
		},
		success: function (result) {
			hideLoading();
			if (result != "success")
				alert("Error! Try again later..");
		},
		error: function (err1, err2, err3) {
			hideLoading();
			alert(err1 + " || " + err2 + " || " + err3);
		}
	});
}

function showLoading() {
	//$("body > *").not(".loading").fadeTo("slow", 0.4);
	$(".loading").fadeIn("slow");
}

function hideLoading() {
	//$("body > *").not(".loading").fadeTo("slow", 1);
	$(".loading").fadeOut("slow");
}